const util = require('../../utils/util.js');
const api = require('../../config/api.js');

//获取应用实例
var app = getApp()
var initProvince = '请选择省';
var initCity = '请选择市';
var initDistrict = '请选择区';

Page({
  onShareAppMessage() {
    return {
      title: '报名',
      path: 'page/signupV3/selctCarModel'
    }
  },
  data: {
    authUrl:'',
    id: null,
    name: '',
    is_default: 0,
    addressData: {},
    jiaxiao: "请选择驾校",
    jiaxiaoId: 0,
    carModel: '请选择车型',
    price: 0,
    navbar_bgcolor: wx.getStorageSync('navbar_bgcolor'),
    classTypeId: 0,
    classType: '请选择班型',
    btnDisabled:true,
    showModal:false,
    dzht:true,
    xbflag:true,
    switch1Checked:false,
    date:'请选择日期',
    carmodels:[],
    index:0,
    carKey:'',
    carVal:'请选择车型',
    num:'0',
    xyht:false,
    htData:{
      name:'',
      sex:'',
      cardNo:'',
      tel:'',
      address:'',
      trainModel:'',
      schoolName:'',
      schoolCardNo:'',
      schoolFddbr:'',
      schoolTel:'',
      schoolAddress:'',
      price:'',
      subject2Price:'',
      subject3Price:'',
      serviceaddress:'',
      servicewww:'',
      servicesite:'',
      serviceroute:'',
      jcMoney:'',
      lcMoney:'',
      day:'',
      subjecttwo:'',
      subjectthree:'',
      tfJcMoney:'',
      tfGlJcMoney:'',
      signImg:''
    },
    context1: null,
    hasDraw:false, //默认没有画
    src:null,
  },

  onLoad: function (e) {
    var that = this;

    var userid = wx.getStorageSync("userid");
    if(userid == ''){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }

    var carModel = wx.getStorageSync("carModel");
    console.log("当前用户选择的驾考类型是："+carModel);
    var schoolId = wx.getStorageSync("schoolId");
    var schoolName = wx.getStorageSync("schoolName");
    console.log(schoolId+"vv当前用户选择的驾考类型是：vv"+schoolName);
    
    that.setData({
      carModel:carModel,
      jiaxiaoId: schoolId ? schoolId : 0,
      jiaxiao: schoolName ? schoolName : "请选择驾校"
    });

    /**清空一下当前选择的驾校信息 */
    wx.setStorageSync("schoolId","");
    wx.setStorageSync("schoolName","");


    util.request(api.signUpGetDetail, {uid:userid})
      .then(function (res) {
        if (res.errno == 0) {
          that.setData({
            id: res.data.id,
            name: res.data.name
            //jiaxiaoId: res.data.schoolId ? res.data.schoolId : 0,
            //jiaxiao: res.data.schoolName ? res.data.schoolName : "请选择驾校",
          });
        } else {
          util.showErrorToast(res.errmsg);
        }
      });


      util.request(api.getAllCarModel)
      .then(function (res) {
        //console.log(JSON.stringify(res.data));
        that.setData({
          carmodels:res.data
        })
      });

      var context1 = wx.createCanvasContext('handWriting1');
      context1.setStrokeStyle("#000000")
      context1.setLineWidth(3);
      this.setData({
        context1: context1,
      })
      // that.getAuthUrl();
    },
    touchstart1: function(e) {
      var context1 = this.data.context1;
      context1.moveTo(e.touches[0].x, e.touches[0].y);
      this.setData({
        context1: context1,
        hasDraw : true, //要签字了
      });
    },
    touchmove1: function(e) {
      var x = e.touches[0].x;
      var y = e.touches[0].y;
      var context1 = this.data.context1;
      context1.setLineWidth(3);
      context1.lineTo(x, y);
      context1.stroke();
      context1.setLineCap('round');
      context1.draw(true);
      context1.moveTo(x, y);
    },
    reSign1: function() { //重新画
      var that = this;
      var context1 = that.data.context1;
      context1.draw(); //清空画布
      that.setData({
        hasDraw: false, //没有画
        src: null
      });
    },
    sign1ok: function () {
      var that = this;
      if(!that.data.hasDraw){
        console.log("签字是空白的 没有签字")
      }else{
        var context1 = that.data.context1;
        context1.draw(true, wx.canvasToTempFilePath({
          canvasId: 'handWriting1',
          success(res) {
            console.log(res.tempFilePath) //得到了图片下面自己写上传吧
            that.setData({
              src: res.tempFilePath
            })
             
          }
        }))
      }
    },
  checkboxChange:function(e){
    // console.log(JSON.stringify(e.detail.value[0]));
    if(typeof(e.detail.value[0]) != 'undefined'){
      this.setData({
        xyht:true
      })
    }else{
      this.setData({
        xyht:false
      })
    }
  },
  // 禁止屏幕滚动
  preventTouchMove:function () {
  },
  changeDate:function(e){
    //console.log('picker发送选择改变，携带值为', e.detail.value);
    var that = this
    that.setData({
      date:e.detail.value
    })
  },
  saveCarModel:function(e){
    var that = this
    //console.log(JSON.stringify(e));
    //console.log('picker发送选择改变，携带值为', e.detail.value);
    var key = e.detail.value;
    var carModel = that.data.carmodels[key];
    that.setData({
      carVal:carModel
    })
  },
  switch1Change:function(){
    var that = this
    //console.log(that.data.switch1Checked);
    if(that.data.switch1Checked){
      that.setData({
        switch1Checked:false
      });
    }else{
      that.setData({
        switch1Checked:true
      });
    }

    //console.log(that.data.switch1Checked);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    var that = this;
    //console.log(that.data.jiaxiaoId+'==='+that.data.classTypeId+'==='+that.data.jiaxiaoId&&that.data.classTypeId);
    // if (that.data.jiaxiaoId && that.data.classTypeId) {
    //   that.setData({
    //     price: "3850"
    //   });
    // }
  },

  bindCancel: function () {
    wx.navigateBack({})
  },
  bindht:function(e){
    //console.log("vvvvvvvvvvvvvvvvv");
    var that = this
    //console.log("that.data.carModel::::::::"+that.data.jiaxiaoId);
    if(that.data.carModel == ''){
      wx.showModal({
        title: '提示',
        content: '无法获取车型信息，请退回到首页进行选择对应的车型！',
        showCancel: false
      })
      return;
    }
    if(that.data.carModel == '请选择车型'){
      wx.showModal({
        title: '提示',
        content: '无法获取车型信息，请退回到首页进行选择对应的车型！',
        showCancel: false
      })
      return;
    }
    if (this.data.jiaxiaoId == 0 || this.data.classTypeId == 0) {
      wx.showModal({
        title: '提示',
        content: '请选择驾校班型信息',
        showCancel: false
      })
      return;
    }
    if(that.data.jiaxiao == '请选择驾校'){
      wx.showModal({
        title: '提示',
        content: '驾校信息获取失败，退回首页重试！',
        showCancel: false
      })
      return;
    }
    /*wx.navigateTo({
      url: '/pages/signup/dzht/dzht',
    })*/
    var userid = wx.getStorageSync("userid");
    var classId = this.data.classTypeId;
    util.request(api.queryHtByUserIdAndClassIdUrl, {userId:userid,classId:classId}).then(function (res) {
      //console.log(JSON.stringify(res));
      //console.log(JSON.stringify(res.data.ht));
      var stu = res.data.stu;
      var classtype = res.data.class;
      var dept = res.data.dept;
      var ht = res.data.ht;
      var num = res.data.num;
      that.setData({
        num:num
      })

      var sex = '女';
      if(stu.gender == '1'){
        sex = '男';
      }
      var dx = that.changeMoneyToChinese(parseInt(classtype.price));


      if(typeof(res.data.ht) == 'undefined'){
        that.setData({
          showModal:false,
          dzht:true,
          xbflag:true,
          'htData.name':stu.name,
          'htData.sex':sex,
          'htData.cardNo':stu.cardNo,
          'htData.tel':stu.mobile,
          'htData.address':stu.address,
          'htData.trainModel':classtype.trainModel,
          'htData.schoolName':dept.name,
          'htData.schoolCardNo':dept.licenseNo,
          'htData.schoolFddbr':dept.legalPerson,
          'htData.schoolTel':dept.phone,
          'htData.schoolAddress':dept.address,
          'htData.price':classtype.price,
          'htData.dx':dx,
          'htData.subject2Price':'0',
          'htData.subject3Price':'0',
          'htData.serviceaddress':'0',
          'htData.servicewww':'0',
          'htData.servicesite':'0',
          'htData.serviceroute':'0',
          'htData.jcMoney':'0',
          'htData.lcMoney':'0',
          'htData.day':'0',
          'htData.subjecttwo':'0',
          'htData.subjectthree':'0',
          'htData.tfJcMoney':'0',
          'htData.tfGlJcMoney':'0'
        })

        wx.showToast({
          title: '当前驾校未设置电子合同的基本信息！',
          icon: "none",
          duration: 1000
        })
      }else{
     
        that.setData({
          showModal:true,
          dzht:false,
          xbflag:false,
          'htData.name':stu.name,
          'htData.sex':sex,
          'htData.cardNo':stu.cardNo,
          'htData.tel':stu.mobile,
          'htData.address':stu.address,
          'htData.trainModel':classtype.trainModel,
          'htData.schoolName':dept.name,
          'htData.schoolCardNo':dept.licenseNo,
          'htData.schoolFddbr':dept.legalPerson,
          'htData.schoolTel':dept.phone,
          'htData.schoolAddress':dept.address,
          'htData.price':classtype.price,
          'htData.dx':dx,
          'htData.subject2Price':ht.kmtwo,
          'htData.subject3Price':ht.kmthree,
          'htData.serviceaddress':ht.serviceaddress,
          'htData.servicewww':ht.servicewww,
          'htData.servicesite':ht.servicesite,
          'htData.serviceroute':ht.serviceroute,
          'htData.jcMoney':ht.jcMoney,
          'htData.lcMoney':ht.lcMoney,
          'htData.day':ht.day,
          'htData.subjecttwo':ht.subjecttwo,
          'htData.subjectthree':ht.subjectthree,
          'htData.tfJcMoney':ht.tfJcMoney,
          'htData.tfGlJcMoney':ht.tfGlJcMoney,
        })
      }

    })
 
    

    /*that.setData({
      dzht:false,
      btnDisabled:true
    })*/
  },
  bindok(){
    var that = this;
    if(!this.data.xyht){
      wx.showModal({
        title: '提示',
        content: '请先认真阅读并同意本合同！',
        showCancel: false
      })
      return;
    }

    if(this.data.num != '0'){
      wx.showToast({
        title: '当前学员存在未学完的车型，不允许重复报名！',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    if(!that.data.hasDraw){
      console.log("签字是空白的 没有签字")
      wx.showModal({
        title: '提示',
        content: '您还没有签字，请先签名！',
        showCancel: false
      })
      return;
    }else{
      var context1 = that.data.context1;
      context1.draw(true, wx.canvasToTempFilePath({
        canvasId: 'handWriting1',
        success(res) {
          // console.log(res.tempFilePath) //得到了图片下面自己写上传吧
          // "'data:image/png;base64,'"+
          var base64Img = wx.getFileSystemManager().readFileSync(res.tempFilePath,'base64');
          that.setData({
            src: res.tempFilePath,
            ['htData.signImg']:base64Img
          })
           that.sendDzhtContent();
           that.bindSave();
        }
      }))


    }
  },
  sendDzhtContent(){
    var that = this
    // console.log(that.data.src);
    // console.log(that.getImageBase64_readFile(that.data.src));
    console.log(JSON.stringify(this.data.htData));
    util.request(api.saveUserHtUrl, this.data.htData,'POST')
    .then(function (res) {
      that.setData({
        showModal:false,
        dzht:false,
        btnDisabled:true,
        xbflag:true
      })
    })
  },
  async getImageBase64_readFile(tempFilePath) {
    
    const {
      width,
      height
    } = await wx.getImageInfo({
      src: tempFilePath
    });
    const base64 = await new Promise(resolve => {
      const query = wx.createSelectorQuery();
      query.select("#myCanvas").fields({
        node: true, // 获取 node
      }).exec(res => {
 
        let {
          node: canvas
        } = res[0];
 
        let ctx = canvas.getContext('2d');
        let image = canvas.createImage();
 
        console.log(image);
        image.src = tempFilePath;
        image.onload = () => {
          ctx.drawImage(image, 0, 0, width, height);
          resolve(canvas.toDataURL())
        }
      });
    });
 
    this.setData({
      base64
    })

  },
  selectJXByModel: function () {
    wx.navigateTo({
      url: '/pages/signup/listByModel/list',
    })
  },
  selectCX: function () {
    wx.navigateTo({
      url: '/pages/signup/chexing/list',
    })
  },
  bindSave: function (e) {
    var that = this;

    //判断是否增驾
    if(that.data.switch1Checked){
      if(that.data.date == '' || that.data.date == '请选择日期'){
        wx.showModal({
          title: '提示',
          content: '请填写初领日期',
          showCancel: false
        })
        return;
      }

      if(that.data.carVal == '' || that.data.carVal == '请选择车型'){
        wx.showModal({
          title: '提示',
          content: '请选择原始车型',
          showCancel: false
        })
        return;
      }
    }

    if (this.data.jiaxiaoId == 0 || this.data.classTypeId == 0) {
      wx.showModal({
        title: '提示',
        content: '请选择驾校班型信息',
        showCancel: false
      })
      return;
    }

    that.setData({
      //btnDisabled:true,
      navbar_bgcolor:'#7993E1'
    })
    wx.showLoading({
      title: '支付中...',
    })

    var userid = wx.getStorageSync("userid");
    if(userid == ''){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }
    util.request(api.signUpUpdate, {
      id: this.data.id,
      name: this.data.name,
      schoolId: this.data.jiaxiaoId,
      schoolName: this.data.jiaxiao,
      classTypeId: this.data.classTypeId,
      classTypeName: this.data.classType,
      uid:userid,
      isbPlusCard:that.data.switch1Checked,
      firstDate:that.data.date,
      laterType:that.data.carVal
    }, "POST")
      .then(function (res) {
        wx.hideLoading()
        // console.log(JSON.stringify(res));
        if (res.errno == 0) {
          // 请求支付参数
          var action = res.data.action;
          var payInfo = res.data.bean;
          that.pay(action, payInfo);
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      }).catch(error => {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: error.errmsg,
          showCancel: false
        })
      });


  },
  //选择班型
  selectBX: function () {
    if (this.data.jiaxiaoId == 0) {
      wx.showModal({
        title: '提示',
        content: '请选择驾校',
        showCancel: false
      })
      return;
    }
    var carModel = wx.getStorageSync("carModel");
    console.log("当前用户选择的驾考类型是："+carModel);

    wx.navigateTo({
      url: '/pages/signupV3/classType/list?sid=' + this.data.jiaxiaoId,
    })
  },
  changeMoneyToChinese(money){  
    var cnNums = new Array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"); //汉字的数字  
    var cnIntRadice = new Array("","拾","佰","仟"); //基本单位  
    var cnIntUnits = new Array("","万","亿","兆"); //对应整数部分扩展单位  
    var cnDecUnits = new Array("角","分","毫","厘"); //对应小数部分单位  
    //var cnInteger = "整"; //整数金额时后面跟的字符  
    var cnIntLast = "元"; //整型完以后的单位  
    var maxNum = 999999999999999.9999; //最大处理的数字  
      
    var IntegerNum; //金额整数部分  
    var DecimalNum; //金额小数部分  
    var ChineseStr=""; //输出的中文金额字符串  
    var parts; //分离金额后用的数组，预定义  
    if( money == "" ){  
        return "";  
    }  
    money = parseFloat(money);  
    if( money >= maxNum ){  
        $.alert('超出最大处理数字');  
        return "";  
    }  
    if( money == 0 ){  
        //ChineseStr = cnNums[0]+cnIntLast+cnInteger;  
        ChineseStr = cnNums[0]+cnIntLast  
        //document.getElementById("show").value=ChineseStr;  
        return ChineseStr;  
    }  
    money = money.toString(); //转换为字符串  
    if( money.indexOf(".") == -1 ){  
        IntegerNum = money;  
        DecimalNum = '';  
    }else{  
        parts = money.split(".");  
        IntegerNum = parts[0];  
        DecimalNum = parts[1].substr(0,4);  
    }  
    if( parseInt(IntegerNum,10) > 0 ){//获取整型部分转换  
        var zeroCount = 0;  
        var IntLen = IntegerNum.length;  
        for(var i=0;i<IntLen;i++ ){  
            var n = IntegerNum.substr(i,1);  
           var p = IntLen - i - 1;  
            var q = p / 4;  
           var m = p % 4;  
            if( n == "0" ){  
                zeroCount++;  
            }else{  
                if( zeroCount > 0 ){  
                    ChineseStr += cnNums[0];  
                }  
                zeroCount = 0; //归零  
                ChineseStr += cnNums[parseInt(n)]+cnIntRadice[m];  
            }  
            if( m==0 && zeroCount<4 ){  
                ChineseStr += cnIntUnits[q];  
            }  
        }  
        ChineseStr += cnIntLast;  
        //整型部分处理完毕  
    }  
    if( DecimalNum!= '' ){//小数部分  
        decLen = DecimalNum.length;  
        for( i=0; i<decLen; i++ ){  
            n = DecimalNum.substr(i,1);  
            if( n != '0' ){  
                ChineseStr += cnNums[Number(n)]+cnDecUnits[i];  
            }  
        }  
    }  
    if( ChineseStr == '' ){  
        //ChineseStr += cnNums[0]+cnIntLast+cnInteger;  
        ChineseStr += cnNums[0]+cnIntLast;  
    }/* else if( DecimalNum == '' ){ 
        ChineseStr += cnInteger; 
        ChineseStr += cnInteger; 
    } */  
    return ChineseStr;  
  },
  //调起微信支付
  pay: function (action, data) {
    var that = this;
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.packages,
      signType: data.signType,
      paySign: data.paySign,
      success: function (res) {
        wx.showToast({
          title: '支付成功', icon: 'success', duration: 5000
        });
        //util.subscribeMessage();
        wx.redirectTo({
          url: '/pages/signupV3/authurl',
        })
        // wx.redirectTo({
        //   url: '/pages/payResult/payResult?status=true',
        // })
      },
      fail: function (res) {
        console.log("缴费失败")
        wx.redirectTo({
          url: '/pages/payResult/payResult?status=false',
        })
      },
      complete: function (res) {
        console.log(JSON.stringify(res));
        //util.subscribeMessage();
      }
    })
  }

})